import {
  FETCH_PROGRAMLIST,
  ADD_PROGRAM,
  DEL_PROGRAMLIST
} from '../mutation-types'
import Service from '../../axios'
import lazyLoading from './menu/lazyLoading'
import openMessageWithType from './utils/message'

const state = {
  programList: [],
  menus: {
    name: '频道分组',
    path: '/tables',
    meta: {
      icon: 'fa-delicious',
      expanded: false,
      link: 'tables/index.vue'
    },
    component: lazyLoading('tables', true),
    children: []
  }
}

const getters = {
  programList: state => state.programList,
  menus: state => state.menus
}

const actions = {
  getProgramList ({ commit }) {
    Service.get('/program/list')
      .then(res => {
        const success = Object.is(res.statusText, 'OK') && Object.is(res.data.ec, 0)
        if (success) commit('FETCH_PROGRAMLIST', res.data.data)
      })
  },
  addProgram ({commit}, data) {
    Service.post('/program/add', data)
      .then(res => {
        const success = Object.is(res.statusText, 'OK') && Object.is(res.data.ec, 0)
        if (success) {
          commit('ADD_PROGRAM', data)
          openMessageWithType('success', '', '节目添加/修改成功')
        } else {
          openMessageWithType('warning', '', '节目添加/修改失败:' + res.data.msg)
        }
      })
      .catch(function (err) {
        openMessageWithType('danger', '', err)
      })
  },
  delProgramList ({commit}, data) {
    if (data.length <= 0) {
      openMessageWithType('warning', '', '没有选择数据，删除失败')
      return
    }
    let request = data.map(makeUrl)
    function makeUrl (param) {
      return '/program/del?program=' + param
    }
    var result = true
    var errmsg = ''
    request.forEach((item, index) => {
      Service.get(item)
        .then(res => {
          let success = Object.is(res.statusText, 'OK') && Object.is(res.data.ec, 0)
          if (success) {
            commit('DEL_PROGRAMLIST', data[index])
          } else {
            errmsg += res.data.msg + ';'
          }
          result = result && success
        })
    })
    if (result) {
      openMessageWithType('success', '', '全部删除成功')
    } else {
      openMessageWithType('warning', '', '删除发生失败:' + errmsg)
    }
  }
}

const mutations = {
  [FETCH_PROGRAMLIST] (state, data) {
    if (data !== null && data.length > 0) {
      data.forEach(item => {
        state.menus.children.push({
          name: item.program,
          path: 'basic',
          meta: {
            label: item.program,
            icon: '',
            link: item.url
          },
          component: lazyLoading('tables/Basic')
        })
      })
    }
    state.programList = data
  },
  [ADD_PROGRAM] (state, data) {
    state.programList.push(data)
  },
  [DEL_PROGRAMLIST] (state, data) {
    state.programList.forEach((item, index) => {
      if (item.program === data) {
        state.programList.splice(index, 1)
      }
    })
  }
}

export default {
  state,
  actions,
  getters,
  mutations
}
